package com.zcsy.manage.web.news;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.news.HelpManual;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.news.IHelpManualService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * @Title: HelpManualController.java
 * @Package： com.zcsy.manage.web.news 
 * @Description: 社区政务控制层管理类
 * @author caiyinli 13277030520@163.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年4月15日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/helpManual")
public class HelpManualController {
	
	@Autowired
	private IHelpManualService helpManualService;
	
	@Autowired
	private ICellInfoService cellInfoService;

	@Autowired
	private IDictService dictService;
	
    /**
     * @Description 返回帮助手册列表页面<br>
     * 
     * @param pNo 当前页码
     * @param title 标题
     * @param req 用户请求
     * @return 返回帮助手册列表页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value="helpManualList" , method = RequestMethod.GET)
    public String helpManualList(Model model, Integer pageType, Integer pNo, Integer pSize, String title,
             HttpServletRequest req){
    	
	    if(pNo == null){
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        //此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
        
        HelpManual helpManual = new HelpManual();

        //获取当前小区id
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        
		//小区id不为空时，设置小区id
		if (StringUtils.isNotEmpty(cellId)) {
			helpManual.setCellId(cellId);
		}
		
        if(StringUtils.isNotEmpty(title)){
        	helpManual.setTitle(title);
        }

	    helpManual.setType(pageType);
	    
        List<HelpManual> helpManuals = helpManualService.selectByKeyword(helpManual);
        PageInfo<HelpManual> info = new PageInfo<HelpManual>(helpManuals);

//		List<CellInfo>  cellInfos = cellInfoService.getAllCellInfo();
//		model.addAttribute("cellInfos",cellInfos);
		
		model.addAttribute("helpManual", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("cellId", cellId);
		model.addAttribute("title", title);
		model.addAttribute("pageType", pageType);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "news/helpmanual/helpManualList";
    }
    
    /**
     * @Description 返回编辑或新增列表页面<br>
     * 
     * @param model
     * @param id 主键id
     * @return 返回编辑或新增列表页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value = "editHelpManual", method = RequestMethod.GET)
    public String selectById(Model model, String id ,String pageType,HttpServletRequest req) {
        try {
            User user  = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            String cellId = user.getCurrentCell().getId();
            if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                model.addAttribute("type", Constants.SAVE_TYPE);
                model.addAttribute("cellId", cellId);
            } else {
                HelpManual helpManual = helpManualService.selectByPrimaryKey(id);
                if(helpManual != null){
                	model.addAttribute("type", Constants.EDIT_TYPE);
                	model.addAttribute("helpManual", helpManual);
                	model.addAttribute("cellId", cellId);
                	//model.addAttribute("manualCellId", helpManual.getCellId());
                }
            }
			//List<CellInfo>  cellInfos = cellInfoService.getAllCellInfo();
			//model.addAttribute("cellInfos",cellInfos);
			
			model.addAttribute("pageType", pageType);
			
        } catch (Exception e) {
        }
        
        return "news/helpmanual/helpManualEdit";
    }
    
    /**
     * @Description 保存或更新方法<br>
     * 1、id不为空且不为0表示更新
     * 2、否则表示编辑
     * 
     * @param title 标题
     * @param type 帮助类型
     * @param answer回答
     * @param helpId 主键id
     * @param request 用户请求
     * @param response 服务器响应
     * @return 1：成功 0：失败
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value = "saveOrUpdateHelpManual", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateHelpManual(String title, String answer, Integer sort, 
    		String helpId, String logo, Integer pageType, HttpServletRequest request) {
        RequestJson result = new RequestJson();
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        try {
        	HelpManual record = new HelpManual();
            record.setTitle(title);
            record.setCellId(cellId);
            record.setAnswer(answer);
            record.setSort(sort);
            record.setLogo(logo);
            record.setUserAccount(user.getLoginname());
            record.setType(pageType);
            
            if(helpId != ""&& !"0".equals(helpId)){
            	record.setId(helpId);
            	record.setUpdateTime(new Date());
            	helpManualService.update(record);
            	LogUtils.insertLog("用户编辑帮助手册信息", user.getId(), request);

            }else{
            	record.setId(UniqueNumberUtils.get18UniqueNumber());
            	record.setSendTime(new Date());
            	helpManualService.insert(record);
            	LogUtils.insertLog("用户新增帮助手册信息", user.getId(), request);
             	//插入一条区域，将当前区域所在的小区绑定依赖关系，有依赖的小区不能被删除
             	CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
             	cellInfo.setIsUsed(Constants.IS_USED);
             	cellInfoService.update(cellInfo);

            }

        }catch (Exception e) {
            result.setSuccess(false);
        }
        
        return result;
    }
    
    /**
     * @Description 批量删除帮助手册方法<br>
     * 
     * @param helpIDs 所需要删除的id集合
     * @param req用户请求
     * @return 1：成功 0：失败
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value = "deleteHelpManual", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deletePage(String helpIDs,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
			String ids[] = helpIDs.split("\\,");
			for (int i = 0; i < ids.length; i++ ) {
				helpManualService.deleteByPrimaryKey(ids[i]);
			}
			result.setSuccess(true);
			LogUtils.insertLog("用户删除帮助手册信息", user.getId(), req);

		} catch (NumberFormatException e) {
	        result.setSuccess(false);
	        result.setMsg("操作失败");
		}
        
        return result;
    }
    /**
     * @Description 常见问题信息详情
     * @author fangli Fanglwj520@163.com
     * @date 2016年5月17日
     * @see
     */
    @RequestMapping(value = "/helpInfodetail", method = RequestMethod.GET)
    public String cellInfoDetail(Model model, String id, String pageType, HttpServletRequest req){
        try {
            HelpManual helpManual = helpManualService.selectByPrimaryKey(id);
            if(helpManual != null){
                model.addAttribute("helpManual", helpManual);
            }
        } catch (Exception e) {
        }
        
        model.addAttribute("pageType", pageType);
        
        return "news/helpmanual/helpManualDetail";
    }
    
    /**
	 * @Description 将选中项置顶
	 * @param id 主键id
	 * @param req 用户请求
	 * @return 响应结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年6月12日
	 * @see 
	 */
	@RequestMapping(value="updateSort" , method = RequestMethod.GET)
	@ResponseBody
    public RequestJson updateSort( String id, HttpServletRequest req){
        RequestJson result = new RequestJson();
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
        	HelpManual helpManual = helpManualService.selectByPrimaryKey(id);
        	if(helpManual != null){
        		helpManual.setUpdateTime(DateUtils.getDate());
        		helpManualService.updateSort(helpManual);
        		LogUtils.insertLog("用户置顶常见问题", user.getId(), req);

        	}
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
       
        return result;
    }
}
